from PyQt5.Qt import *


class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('demo_337_qstackedlayout')
        self.resize(500, 500)
        self.setup_ui()
        QMetaObject.connectSlotsByName(self)

    def setup_ui(self):
        self.stackedlayout_test()

    def stackedlayout_test(self):
        stack_layout = QStackedLayout()
        self.setLayout(stack_layout)

        label1 = QLabel('标签1')
        label1.setObjectName('label1')

        label2 = QLabel('标签2')
        label2.setObjectName('label2')

        label3 = QLabel('标签3')
        label3.setObjectName('label3')

        label5 = QLabel('标签5')
        label5.setObjectName('label5')

        label6 = QLabel('标签6')
        label6.setObjectName('label6')

        label7 = QLabel('标签7')
        label7.setObjectName('label7')

        self.setStyleSheet("""
                                 QLabel#label1{
                                    background-color: cyan;
                                }
                                QLabel#label2{
                                    background-color: yellow;
                                }
                                QLabel#label3{
                                    background-color: red;
                                }
                                QLabel#label5{
                                    background-color: pink;
                                }
                                QLabel#label6{
                                    background-color: blue;
                                }
                                QLabel#label7{
                                    background-color: cyan;
                                }
                            """)
        h_layout = QHBoxLayout()
        h_layout.addWidget(label5)
        h_layout.addWidget(label6)
        h_layout.addWidget(label7)

        print(stack_layout.addWidget(label1))
        print(stack_layout.addWidget(label2))
        print(stack_layout.addWidget(label3))
        print(stack_layout.addItem(h_layout))
        print('before insert label4,current index is', stack_layout.currentIndex())

        print('insert label4')
        label4 = QLabel('标签4')
        label4.setObjectName('label4')
        print(stack_layout.insertWidget(0, label4))
        print('after insert label4,current index is', stack_layout.currentIndex())

        # get widget by index
        print(stack_layout.widget(3).text())

        timer = QTimer(self)
        timer.timeout.connect(lambda: stack_layout.setCurrentIndex(
            (stack_layout.currentIndex() + 1) % stack_layout.count()
        ))
        timer.start(1000)

        stack_layout.currentChanged.connect(lambda val: print('index changed as:', val))


if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)

    win = Window()
    win.show()
    
    sys.exit(app.exec_())
